package lujieni.starter.config;

import lujieni.starter.mark.LujieniStarterMark;
import lujieni.starter.serializer.FastJsonRedisSerializer;
import lujieni.starter.storage.RedisCacheStorage;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@ConditionalOnBean(value = LujieniStarterMark.class)
@ConditionalOnClass(RedisOperations.class)
@AutoConfigureAfter({RedisAutoConfiguration.class})
public class RedisStorageAutoConfiguration {
    public RedisStorageAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean(name = {"redisCacheStorage"})
    public RedisCacheStorage redisCacheStorage(@Qualifier("redisTemplate") RedisTemplate redisTemplate) {
        RedisCacheStorage storage = new RedisCacheStorage();
        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setHashKeySerializer(serializer);
        redisTemplate.setHashValueSerializer(serializer);
        storage.setRedisTemplate(redisTemplate);
        return storage;
    }

}
